package queue;

public class MyCircularQueue {

    private int[] array;
    private int head;
    private int end;

    public MyCircularQueue(int k) {
        this.array = new int[k+1];
        this.head = this.end = 0;
    }

    public boolean enQueue(int value) {
        if (isFull()) {
            return false;
        }
        array[end] = value;
        end = (end + 1) % array.length;
        return true;
    }

    public boolean deQueue() {
        if (isEmpty()) {
            return false;
        }
        head = (head + 1) % array.length;
        return true;
    }

    public int Front() {
        if (isEmpty()) {
            return -1;
        }
        return array[head];
    }

    public int Rear() {
        if (isEmpty()) {
            return -1;
        }
        return array[(end - 1 + array.length) % array.length];
    }

    public boolean isEmpty() {
        return head == end;
    }

    public boolean isFull() {
        return (end + 1) % array.length == head;
    }

    public static void main(String[] args) {
        MyCircularQueue circularQueue = new MyCircularQueue(3); // 设置长度为 3
        System.out.println(circularQueue.enQueue(1)); // 返回 true
        System.out.println(circularQueue.enQueue(2)); // 返回 true
        System.out.println(circularQueue.enQueue(3)); // 返回 true
        System.out.println(circularQueue.enQueue(4)); // 返回 false，队列已满
        System.out.println(circularQueue.Rear()); // 返回 3
        System.out.println(circularQueue.isFull()); // 返回 true
        System.out.println(circularQueue.deQueue()); // 返回 true
        System.out.println(circularQueue.enQueue(4)); // 返回 true
        System.out.println(circularQueue.Rear()); // 返回 4

    }
}
